// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-2ga6780q302b7f4a'
}) // 使用当前云环境
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  
  try {
    // 验证管理员身份
    const result = await cloud.callFunction({
      name: 'checkAdminAuth',
      data: {
        adminId: event.adminId || '',
        token: event.token || ''
      }
    })
    
    const { code, data } = result.result
    
    if (code !== 0 || !data) {
      return {
        code: 401,
        data: null,
        message: '未授权访问'
      }
    }
    
    // 参数验证
    if (!event.orderId) {
      return {
        code: -1,
        data: null,
        message: '订单ID不能为空'
      }
    }
    
    // 查询订单
    const { data: order } = await db.collection('orders').doc(event.orderId).get()
    
    if (!order) {
      return {
        code: -1,
        data: null,
        message: '订单不存在'
      }
    }
    
    if (order.status !== '借用中') {
      return {
        code: -1,
        data: null,
        message: '该订单已归还或已取消'
      }
    }
    
    // 计算是否逾期
    const now = new Date()
    const returnDeadline = new Date(order.returnDeadline)
    const isOverdue = now > returnDeadline
    
    // 计算信用分变化
    let creditChange = 1 // 默认归还加1分
    
    if (isOverdue) {
      // 逾期扣分，每天扣1分
      const days = Math.ceil((now - returnDeadline) / (24 * 60 * 60 * 1000))
      creditChange = -days
    }
    
    // 更新订单状态
    await db.collection('orders').doc(event.orderId).update({
      data: {
        status: '已归还',
        actualReturnTime: db.serverDate(),
        isOverdue: isOverdue,
        creditChange: creditChange,
        adminId: data.adminId,
        updateTime: db.serverDate()
      }
    })
    
    // 更新装备状态
    await db.collection('equipment').doc(order.equipmentId).update({
      data: {
        status: '可借用', // 恢复为可借用
        updateTime: db.serverDate()
      }
    })
    
    // 更新用户信用分
    await db.collection('users').doc(order.userId).update({
      data: {
        creditScore: db.command.inc(creditChange)
      }
    })
    
    return {
      code: 0,
      data: {
        creditChange,
        isOverdue
      },
      message: '确认归还成功'
    }
  } catch (err) {
    return {
      code: 500,
      data: null,
      message: '确认归还失败: ' + err.message
    }
  }
} 